$(function () {
    // 采购申请信息
    vm.purchaseApplySearch();

    // 获取耗材分类树信息
    $.get(baseURL + "purchase/storepurchaseapply/getEnumList", function(r){
        vm.materialCategoryList = r.materialCategoryTree;
        vm.e.materialUnitEnum = r.materialUnitEnum;
        vm.e.materialSupplier = r.materialSupplier;
        vm.e.purchaseApplyStatusEnum = r.purchaseApplyStatusEnum;
    });
});

var vm = new Vue({
    el:'#rrapp',
	ssm: null,
    data:{
        showList: true,
		Toboolean: false,
        page:{
            current:1, // 当前页
            size:10, // 分页数
            total:0, // 总条数
        },
        applyPage:{
            current:1, // 当前页
            size:15, // 分页数
            total:0, // 总条数
            tableData:[], //数据列
        },
        applyTableHeight:  window.innerHeight - 100, // table高度
        q: {
            applyNo: null,
            sellerId: null,
            status: null,
        },
        e: {
            materialUnitEnum : [],
			purchaseApplyStatusEnum: [],
            materialSupplier: [], /*采购供应商*/
            taxEnum:[{value: 1,label: '含税'},{value: 0,label: '不含税'}],
            //采购类型
            purchaseTypeList: [
                {value: 0,label: '普通耗材'},
                {value: 1,label: '纸张'}
            ],
        },

        materialCategorySearch: '',
        materialCategoryList: [],
        defaultProps: {
            children: 'children',
            label: 'label'
        },
        materialTableData: [],
        purchaseApplyForm: {
            storePurchaseApplyEntity:{
                totalMoney: 0.00,
                tax: null,
                remark: null,
				applyRemark: null,
            },
            storePurchaseApplyDetailEntityList: []
        },
        materialSearchForm: {
            materialName: null
        },
        addMaterialList: [] // 已添加耗材ID集合
    },
    watch: {
        materialCategorySearch(val) {
            this.$refs.tree2.filter(val);
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
        	vm.Toboolean = false;
            vm.showList = false;
            vm.storePurchaseApply = {};
            vm.purchaseApplyForm = {
                storePurchaseApplyEntity:{
                    totalMoney: 0.00,
                    tax: 1,
                    remark: null,
                },
                storePurchaseApplyDetailEntityList: []
            }
            vm.addMaterialList = [];
            vm.materialTableData = [];
            console.log(vm.e.taxEnum)
        },
        onSubmit: function (event) {
            var that = this
            var boolean = false;
            for(var i = 0;i<this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length;i++){
                if(typeof this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].supplierId === "undefined"){
                    alert("采购供应商不能为空");
                    return false;
                }
                if(this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney == 0){
					if(i == this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length-1){
						var materialId = this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].materialId;
						alert("请维护耗材ID是"+materialId+" 的总价");
						return false;
					}else{
						var materialId = this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].materialId;
						alert("请维护耗材ID是"+materialId+" 的总价");
						return false;
					}
                }else if(typeof this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney != "undefined" && i == this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length-1){
                	boolean = true;
                	if(this.purchaseApplyForm.storePurchaseApplyDetailEntityList[0].applyNo!=undefined){
						that.updateSubmit(boolean)
					}else{
						that.saveInfo(boolean)
					}

                }
            }

        },
        saveInfo: function(boolean) {
			if(boolean){
				$.ajax({
					type: "POST",
					async: true,
					url: baseURL + "purchase/storepurchaseapply/save",
					contentType: "application/json",
					data: JSON.stringify(this.purchaseApplyForm),
					success: function (r) {
						if (r.code === 0) {
							alert('操作成功', function (index) {
								vm.reload();
							});
						} else {
							alert(r.msg);
						}
					}
				});
			}
        },

		updateSubmit: function (boolean) {
			if(boolean) {
				$.ajax({
					type: "POST",
					async: true,
					url: baseURL + "purchase/storepurchaseapply/update",
					contentType: "application/json",
					data: JSON.stringify(this.purchaseApplyForm),
					success: function (r) {
						if (r.code === 0) {
							alert('操作成功', function (index) {
								vm.reload();
							});
						} else {
							alert(r.msg);
						}
					}
				});
			}
		},

        getInfo: function(applyId){
            $.get(baseURL + "purchase/storepurchaseapply/info/"+applyId, function(r){
                vm.storePurchaseApply = r.storePurchaseApply;
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.purchaseApplySearch();
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        materialsSearchTwo(data){
            vm.page.current = 1;
            vm.materialsSearch(data);
        },
        /*查询耗材*/
        materialsSearch(data) {
        	if(typeof(data.id) != "undefined"){
				this.ssm = data.id;
			}
            var  paramData = {}
            if(typeof(data.id) == "undefined"){
                paramData.materialName =  this.materialSearchForm.materialName;
				paramData.categoryId = this.ssm;
            }else{
                paramData.categoryId = data.id;
                this.materialSearchForm.materialName = null;
            }
            var queryData = {page: this.page, params: paramData};
            //ajax 请求
            $.ajax({
                type: "POST",
                url: baseURL + "purchase/storepurchaseapply/queryMaterialsList",
                contentType: "application/json",
                data: JSON.stringify(queryData),
                success: function (r) {
                    if (r.code == 0) {
                        vm.page.size = r.page.size;
                        vm.page.total = r.page.total;
                        vm.materialTableData = r.page.records;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /*分页数改变*/
        handleSizeChange(val) {
            vm.page.size = val;
            this.materialsSearch(val);
        },
        /*分页当前页改变改变*/
        handleCurrentChange(val) {
            this.page.current = val
            this.materialsSearch(val);
        },
        /*格式化 单位*/
        formatUnit: function (row, column, cellValue, index) {
            for(var i=0; i<this.e.materialUnitEnum.length; i++){
                if(cellValue == this.e.materialUnitEnum[i].id){
                    return this.e.materialUnitEnum[i].describe
                }
            }
        },
        // 格式化 采购申请状态
        formatStatus: function (row, column, cellValue, index) {
            for(var i=0; i<this.e.purchaseApplyStatusEnum.length; i++){
                if(cellValue == this.e.purchaseApplyStatusEnum[i].id){
                    return this.e.purchaseApplyStatusEnum[i].describe
                }
            }
        },
        // 格式化 采购类型
        formatPurchaseType: function (row, column, cellValue, index) {
            for(var i=0; i<this.e.purchaseTypeList.length; i++){
                if(cellValue == this.e.purchaseTypeList[i].value){
                    return this.e.purchaseTypeList[i].label
                }
            }
        },
        /*格式化 含税*/
        formatTax: function (row, column, cellValue, index) {
            for(var i=0; i<this.e.taxEnum.length; i++){
                if(cellValue == this.e.taxEnum[i].value){
                    return this.e.taxEnum[i].label
                }
            }
        },
        /*添加耗材到采购列表*/
        addMaterial: function (row) {
            if(this.addMaterialList.indexOf(row.materialId)>=0){
                alert("耗材："+row.materialName+" 已添加！")
                return;
            }
            for(var i = 0;i<this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length;i++){
            	if(this.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].materialId == row.materialId){
					alert("耗材："+row.materialName+" 已添加！")
					return;
				}
			}
            var storePurchaseApplyDetail = {
                materialId:row.materialId,
                materialName:row.materialName,
                specifications:row.specifications,
				materialModel:row.materialModel,
				length:row.length,
				width:row.width,
				supplierId:row.supplierId,
                showUnit:row.showUnit,
                materialQuantity:1,
                totalMoney:0,
                weight:row.weight
            }
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.push(storePurchaseApplyDetail);
            this.addMaterialList.push(row.materialId);
        },
        /*移除采购列表耗材*/
        removePurchaseMaterials: function (row,index) {
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1)

            var materialIdIndex = vm.addMaterialList.indexOf(row.materialId);
            vm.addMaterialList.splice(materialIdIndex,1);

            vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
                - Number(row.totalMoney)
        },
        /*单个耗材，采购总价修改事件*/
        totalMoneyChange: function (row,index) {
            var storePurchaseApplyDetail = this.purchaseApplyForm.storePurchaseApplyDetailEntityList[index];
            storePurchaseApplyDetail.unitMoney = percentNum(storePurchaseApplyDetail.totalMoney,storePurchaseApplyDetail.materialQuantity)
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1,storePurchaseApplyDetail);

            // 修改采购总价
            this.changePurchaseTotal();
        },
        // 修改采购总价
        changePurchaseTotal: function () {
            vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = 0.00
            for(var i=0; i<this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length; i++){
                vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
                    + Number(vm.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney);
            }
        },
        /*分页数改变*/
        applySizeChange(val) {
            this.applyPage.size = val;
            this.purchaseApplySearch();
        },
        /*分页当前页改变改变*/
        applyCurrentChange(val) {
            this.applyPage.current = val
            this.purchaseApplySearch();
        },
        // 采购申请查询
        purchaseApplySearch: function () {
            var pageData = {
                'list':[],
                'totalCount':vm.applyPage.total,
                'pageSize':vm.applyPage.size,
                'current':vm.applyPage.current,
            }
            var query = {
                page: pageData,
                params: this.q
            };
            //ajax 请求
            $.ajax({
                type: "POST",
                url: baseURL + "purchase/storepurchaseapply/querylistPage",
                contentType: "application/json",
                data: JSON.stringify(query),
                success: function (r) {
                    if (r.code == 0) {
                        vm.applyPage.size = r.page.size;
                        vm.applyPage.total = r.page.total;
                        vm.applyPage.tableData = r.page.records;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        // 采购申请审核
        audit: function (row) {
            window.storepurchaseapplyAuditVm.loadData({
                'materialUnitEnum':this.e.materialUnitEnum,
                'storePurchaseApply': row,
                'materialSupplier':this.e.materialSupplier,
                'purchaseTypeList':this.e.purchaseTypeList,
            });
        },
		materialwindow: function (row) {
			vm.Toboolean = true;
        	if(row.status!=1){
        		alert("请确认当前是待审核状态");
        		return
			}
			$.ajax({
				type: "POST",
				url: baseURL + "purchase/storepurchaseapply/querylistDetail/"+row.applyNo,
				contentType: "application/json",
				data: JSON.stringify(row.applyNo),
				success: function (r) {
					if (r.code == 0) {
						vm.$set(vm.purchaseApplyForm,'storePurchaseApplyDetailEntityList',r.materialByinNo);
					} else {
						alert(r.msg);
					}
				}
			});
			vm.showList = false;
			vm.storePurchaseApply = {};
			vm.purchaseApplyForm = {
				storePurchaseApplyEntity:{
					totalMoney:row.totalMoney,
					tax:row.tax,
					applyRemark:row.applyRemark,
                    purchaseType:row.purchaseType,
				},
			}
			vm.addMaterialList = [];
			vm.materialTableData = [];
			console.log(vm.e.taxEnum);
		},
        //查询条件重置
        reset:function(){
            vm.q.applyNo = null;
            vm.q.status = null;
        }
    }
});

function percentNum(num,num2) {
    return ((num / num2).toFixed(4));
}